package com.qf.fmw.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        //1.生成图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.获取画笔对象
        Graphics graphics = image.getGraphics();
        //3.选择颜色
        graphics.setColor(Color.PINK);
        //4.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //5.改变画笔颜色
        graphics.setColor(Color.BLUE);
        //6.选择字体
        graphics.setFont(new Font("宋体",Font.BOLD,20));
        //7.生成随机数并添加到指定位置
        Random ran = new Random();
        StringBuffer sb = new StringBuffer();
        String code;
        for (int i = 0; i < 4; i++) {
            code = ran.nextInt(10)+"";
            sb.append(code);
            graphics.drawString(code,15+i*20,ran.nextInt(10)+30);
        }
        //把服务器生成的验证码存放到会话作用域中
        HttpSession session = req.getSession();
        session.setAttribute("serverCode",sb.toString());
        //8.改变画笔颜色
        graphics.setColor(Color.GREEN);
        //9.绘制干扰线
        for (int i = 0; i < 10; i++) {
            graphics.drawLine(ran.nextInt(width),ran.nextInt(height),ran.nextInt(width),ran.nextInt(height));
        }
        //10.把验证码图片发送给前端
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}
